<template>
    <div class="app-container">
      <el-row :gutter="20" class="header">
        <el-col :span="7">
          <el-input 
            placeholder="请输入岗位名称..." 
            v-model="queryForm.query" 
            clearable
            @keyup.enter="initGangweiList"
          ></el-input>
        </el-col>
        <el-col :span="7">
          <el-select
            v-model="queryForm.query2"
            placeholder="请选择部门"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in bumenOptions"
              :key="item.id"
              :label="item.bumen"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-button type="primary" :icon="Search" @click="initGangweiList">搜索</el-button>
        <el-button type="success" :icon="DocumentAdd" @click="handleAdd">新增</el-button>
        <el-popconfirm 
          title="您确定批量删除这些记录吗？" 
          @confirm="handleBatchDelete"
        >
          <template #reference>
            <el-button type="danger" :disabled="!selectedRows.length" :icon="Delete">
              批量删除
            </el-button>
          </template>
        </el-popconfirm>
      </el-row>
  
      <el-table 
        :data="tableData" 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="gangwei" label="岗位名称" width="200" align="center" />
        <el-table-column prop="bumenName" label="所属部门" width="150" align="center" />
        <el-table-column prop="addtime" label="创建时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDate(row.addtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{row}">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)" />
            <el-popconfirm 
              title="您确定要删除这条记录吗？" 
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" :icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination
        v-model:currentPage="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  
      <!-- 新增/编辑对话框 -->
      <el-dialog 
        v-model="dialogVisible" 
        :title="dialogTitle" 
        width="500px"
        @closed="resetForm"
      >
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="formRef" 
          label-width="100px"
        >
          <el-form-item label="所属部门" prop="query2">
            <el-select
              v-model="formData.query2"
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="item in bumenOptions"
                :key="item.id"
                :label="item.bumen"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位名称" prop="gangwei">
            <el-input 
              v-model="formData.gangwei" 
              placeholder="请输入岗位名称" 
              clearable
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitting"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, onMounted } from 'vue'
  import { Search, Delete, DocumentAdd, Edit } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import requestUtil, { getServerUrl } from "@/util/request"
  
  export default {
    setup() {
      // 响应式数据
      const tableData = ref([])
      const loading = ref(false)
      const total = ref(0)
      const selectedRows = ref([])
      const bumenOptions = ref([])
      const dialogVisible = ref(false)
      const dialogTitle = ref('')
      const submitting = ref(false)
      const formRef = ref(null)
  
      const queryForm = ref({
        query: '',
        query2: '',
        pageNum: 1,
        pageSize: 10
      })
  
      const formData = ref({
        id: undefined,
        gangwei: '',
        query2: undefined
      })
  
      const rules = {
        query2: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        gangwei: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
        ]
      }
  
      // 方法
      const initBumenOptions = async () => {
        try {
          const res = await requestUtil.post("sys/bumen/all", queryForm.value)
          if (res.data?.code === 200) {
            bumenOptions.value = res.data.list;
          }
          console.log('部门选项数据2:', bumenOptions.value); // 打印到控制台
        } catch (error) {
          console.error('获取部门列表失败:', error)
          ElMessage.error('获取部门列表失败')
        }
      }
  
      const initGangweiList = async () => {
        try {
          loading.value = true
          const res = await requestUtil.post("sys/gangwei/list", queryForm.value)
          const allIds = bumenOptions.value.map(item => item.id);
          if (res.data?.code === 200) {
            tableData.value = (res.data.list || []).map(item => {
              const bumen = bumenOptions.value.find(b => b.id === item.bumenid)
              console.log("bumen",bumen);
              return {
                ...item,
                bumenName: bumen ? bumen.bumen : '未知部门'
              }
            })
            total.value = res.data.total || 0
          } else {
            throw new Error(res.data?.msg || '返回数据格式不正确')
          }
        } catch (error) {
          ElMessage.error('获取数据失败: ' + (error.response?.data?.msg || error.message))
        } finally {
          loading.value = false
        }
      }
  
      const handleSizeChange = (size) => {
        queryForm.value.pageSize = size
        queryForm.value.pageNum = 1
        initGangweiList()
      }
  
      const handleCurrentChange = (page) => {
        queryForm.value.pageNum = page
        initGangweiList()
      }
  
      const handleSelectionChange = (selection) => {
        selectedRows.value = selection
      }
  
      const handleAdd = () => {
        dialogTitle.value = '新增岗位'
        dialogVisible.value = true
      }
  
      const handleEdit = (row) => {
        dialogTitle.value = '编辑岗位'
        formData.value = { ...row }
        dialogVisible.value = true
      }
  
      const submitForm = async () => {
        try {
          await formRef.value.validate()
          submitting.value = true
          
          const api = "sys/gangwei/save"
          const res = await requestUtil.post(api, formData.value)
          
          if (res.data?.code === 200) {
            ElMessage.success(res.data.msg || '操作成功')
            dialogVisible.value = false
            initGangweiList()
          } else {
            ElMessage.error(res.data?.msg || '操作失败')
          }
        } catch (error) {
          console.error(error)
        } finally {
          submitting.value = false
        }
      }
  
      const handleDelete = async (id) => {
        try {
          await ElMessageBox.confirm('确定要删除该岗位吗?', '提示', {
            type: 'warning'
          })
          
          const res = await requestUtil.post("sys/gangwei/delete", [id])
          if (res.data?.code === 200) {
            ElMessage.success('删除成功')
            initGangweiList()
          } else {
            ElMessage.error(res.data?.msg || '删除失败')
          }
        } catch (error) {
          console.error(error)
        }
      }
  
      const handleBatchDelete = async () => {
        if (!selectedRows.value.length) return
        
        try {
          await ElMessageBox.confirm(
            `确定要删除选中的${selectedRows.value.length}条记录吗?`, 
            '提示', 
            { type: 'warning' }
          )
          
          const ids = selectedRows.value.map(item => item.id)
          const res = await requestUtil.post("sys/gangwei/delete", ids)
          
          if (res.data?.code === 200) {
            ElMessage.success('批量删除成功')
            selectedRows.value = []
            initGangweiList()
          } else {
            ElMessage.error(res.data?.msg || '批量删除失败')
          }
        } catch (error) {
          console.error(error)
        }
      }
  
      const resetForm = () => {
        formRef.value?.resetFields()
        formData.value = {
          id: undefined,
          gangwei: '',
          query2: undefined
        }
      }
  
      const formatDate = (dateStr) => {
        if (!dateStr) return ''
        const date = new Date(dateStr)
        return date.toLocaleString()
      }
  
      // 生命周期
      onMounted(() => {
        initBumenOptions()
        initGangweiList()
      })
  
      // 暴露给模板
      return {
        tableData,
        loading,
        total,
        selectedRows,
        bumenOptions,
        dialogVisible,
        dialogTitle,
        submitting,
        formRef,
        queryForm,
        formData,
        rules,
        Search,
        Delete,
        DocumentAdd,
        Edit,
        initGangweiList,
        handleSizeChange,
        handleCurrentChange,
        handleSelectionChange,
        handleAdd,
        handleEdit,
        submitForm,
        handleDelete,
        handleBatchDelete,
        resetForm,
        formatDate
      }
    }
  }
  </script>
  
  
  <style lang="scss" scoped>
  .app-container {
    padding: 20px;
    height: calc(100vh - 40px); /* 添加高度限制 */
    display: flex;
    flex-direction: column;
  }
  
  .header {
    margin-bottom: 20px;
    .el-col {
      margin-right: 10px;
    }
  }
  
  /* 表格容器样式 */
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .el-table {
      flex: 1;
      width: 100% !important;
      
      ::v-deep .el-table__body-wrapper {
        overflow-x: auto;
      }
    }
  }
  
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
    flex-shrink: 0; /* 防止分页被压缩 */
  }
  
  /* 表格单元格样式 */
  ::v-deep .el-table {
    .el-table__cell {
      padding: 8px 0;
    }
    
    th.el-table__cell {
      background-color: #f8f9fa !important;
      color: #515a6e;
      font-weight: bold;
    }
    
    /* 让表格列自动分配宽度 */
    .el-table__header-wrapper .el-table__header,
    .el-table__body-wrapper .el-table__body {
      width: 100% !important;
    }
    
    /* 固定最后一列操作栏 */
    .el-table__fixed-right {
      height: 100% !important;
    }
  }
  
  .el-button + .el-button {
    margin-left: 8px;
  }
  </style>
